'use strict';

const { Service } = require('egg');
const Result = require('../util/result');

class TrainlineService extends Service {
  async findAll(query) {
    const info = await this.ctx.model.Trainline.findAll(query);
    return Result.success(info);
  }

  async update(id, data) {
    const info = await this.ctx.model.Trainline.update({ ...data }, {
      where: { id },
    });
    if (info === 0) return Result.fail();
    const res = await this.findOne(id);
    return Result.success(res);
  }

  async create(data) {
    const info = await this.ctx.model.Trainline.create({ ...data });
    const res = {
      id: info.id,
      train_id: info.train_id,
      train_name: info.train_name,
      station_info: info.station_info,
    };
    return Result.success(res);
  }

  async destroy(id) {
    const info = await this.findOne(id);
    if (!info) return Result.fail();
    const row = this.ctx.model.Trainline.destroy({
      where: { id },
    });
    if (row === 0) return Result.fail();
    return Result.noDataSuccess();
  }

  async findOne(id) {
    const info = await this.ctx.model.Trainline.findByPk(id);
    return info;
  }
}

module.exports = TrainlineService;
